package com.senmiao.ssm.realm;

import com.senmiao.ssm.mapper.AdminMapper;
import com.senmiao.ssm.entity.Admin;
import com.senmiao.ssm.service.AccessControlService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private AccessControlService accessControlService;

    public MyRealm() {
        // 指定密码匹配器
//        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(MyConstants.HASH_ALGORITHM_NAME);
//        hashedCredentialsMatcher.setHashIterations(MyConstants.HASH_ITERATIONS);
//        setCredentialsMatcher(hashedCredentialsMatcher);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = principalCollection.getPrimaryPrincipal().toString();
        // 拿角色信息
        Set<String> roles =  accessControlService.listRolesByUsername(username);
        // 拿权限信息
        Set<String> permissions =  accessControlService.listPermissionsByUsername(username);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(roles);
        simpleAuthorizationInfo.setStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    /**
     * 登录
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = authenticationToken.getPrincipal().toString();
        // 从数据库中拿登录信息
        Admin admin = accessControlService.findPasswordByUsername(username);
        if (admin == null)throw new IncorrectCredentialsException();
        return new SimpleAuthenticationInfo(username,admin.getPassword(), getName());
    }
}